package com.jfee.dds.config;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import lombok.ToString;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;

@Data
@ToString
@Component
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidPropertiesConfig extends DruidDataSource implements InitializingBean {
    @Autowired
    private DataSourceProperties basicProperties;

    DruidPropertiesConfig() {
    }

    public void afterPropertiesSet() throws Exception {
        if (this.getUsername() == null) {
            this.setUsername(this.basicProperties.determineUsername());
        }

        if (this.getPassword() == null) {
            this.setPassword(this.basicProperties.determinePassword());
        }

        if (this.getUrl() == null) {
            this.setUrl(this.basicProperties.determineUrl());
        }

        if (this.getDriverClassName() == null) {
            this.setDriverClassName(this.basicProperties.getDriverClassName());
        }

    }


    @Autowired(
            required = false
    )
    public void autoAddFilters(List<Filter> filters) {
        this.filters.addAll(filters);
    }

}
